﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace XUtility
{
    public static class CacheClass
    {

        /// <summary>
        /// 保存数据到缓存里
        /// </summary>
        /// <param name="p_key">键</param>
        /// <param name="p_value">值</param>
        /// <param name="saveMinutes">保存几分钟，默认10分钟</param>
        /// <param name="dependenFilePath">文件缓存依赖</param>
        /// <returns></returns>
        public static Boolean SetCache(String p_key, object p_value, Int32 saveMinutes = 10, String dependenFilePath = null)
        {
            try
            {
                if (dependenFilePath.HasValue())
                {
                    var dep = new CacheDependency(dependenFilePath);
                    HttpRuntime.Cache.Add(p_key, p_value, dep, DateTime.Now.AddMinutes(saveMinutes), Cache.NoSlidingExpiration,
                                CacheItemPriority.Normal, null);
                }
                else
                {
                    HttpRuntime.Cache.Add(p_key, p_value, null, DateTime.Now.AddMinutes(saveMinutes), Cache.NoSlidingExpiration,
                                CacheItemPriority.Normal, null);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 从缓存中查找数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p_key"></param>
        /// <returns></returns>
        public static T GetCache<T>(String p_key) where T : class
        {
            try
            {
                var cac = HttpRuntime.Cache[p_key];
                if (cac == null)
                {
                    return null;
                }
                return JsonClass.FromJson<T>(cac.ToJson()); // 深度复制，避免地址引用
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="p_key"></param>
        /// <returns></returns>
        public static XJsonInfo RemoveCache(String p_key)
        {
            try
            {
                HttpRuntime.Cache.Remove(p_key);
                return new XJsonInfo();
            }
            catch (Exception ex)
            {
                return new XJsonInfo(false, ex.Message);
            }
        }
    }
}
